<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="workbench-form">
      <el-form-item label="载体">
        <el-select
          v-model="queryParams.zt"
          placeholder="请选择载体"
          style="width: 200px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in carrierList"
            :key="item.nr"
            :label="item.nr"
            :value="item.nr"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          style="width: 140px"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  <!-- 项目数据看板及图表 -->
    <el-row :gutter="18" class="board-row">
      <el-col :span="8">
        <el-card class="board-card income-bg" shadow="hover">
          <div class="board-title">营收统计</div>
          <div class="board-value-group">
            <div>
              <div class="board-label">月度总应收</div>
              <div class="board-value">{{ boardData.dbjsdfb ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">租用总应收</div>
              <div class="board-value">{{ boardData.hkzyjeb ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">租用已收</div>
              <div class="board-value">{{ boardData.hkysjeb ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">租用未收</div>
              <div class="board-value">{{ boardData.hkwsjeb ?? '--' }}</div>
            </div>
          </div>
          <div ref="incomePieChart" style="width:100%;height:200px;margin-top:12px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="board-card power-bg" shadow="hover">
          <div class="board-title">电量统计</div>
          <div class="board-value-group">
            <div>
              <div class="board-label">电表总电量</div>
              <div class="board-value">{{ boardData.dbjsa ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">租用总电量</div>
              <div class="board-value">{{ boardData.dbzya ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">月度整体电费</div>
              <div class="board-value">{{ boardData.dbjsdfa ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">空调费已收</div>
              <div class="board-value">{{ boardData.kkysjec ?? '--' }}</div>
            </div>
          </div>
          <div ref="powerBarChart" style="width:100%;height:200px;margin-top:12px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="board-card invoice-bg" shadow="hover">
          <div class="board-title">开票统计</div>
          <div class="board-value-group">
            <div>
              <div class="board-label">已开票</div>
              <div class="board-value">{{ boardData.kpjec ?? '--' }}</div>
            </div>
            <div>
              <div class="board-label">待开票</div>
              <div class="board-value">{{ boardData.dkpjec ?? '--' }}</div>
            </div>
          </div>
          <div ref="invoicePieChart" style="width:100%;height:200px;margin-top:12px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 项目分布图（地图/柱状图） -->
    <!-- <el-card class="map-card" shadow="hover">
      <div class="map-title">项目分布</div>
      <div ref="projectMapChart" style="width:100%;height:320px;"></div>
    </el-card> -->

  

    <!-- 租户数据图表 -->
    <el-card class="tenant-chart-card" shadow="hover" >
      <div class="tenant-chart-title">租户电费分布</div>
      <div ref="tenantBarChart" style="width:100%;height:320px;"></div>
    </el-card>

    <!-- 租户虚拟列表卡片 -->
    <el-card class="tenant-list-card" shadow="hover">
      <div class="tenant-list-title">租户明细</div>
      <el-table
        :data="tenantList"
        v-loading="tenantLoading"
        style="width: 100%;"
        @row-click="showTenantDetail"
        highlight-current-row
        size="small"
      >
        <el-table-column prop="qymc" label="企业名称" min-width="180" />
        <el-table-column prop="hkjeb" label="应收电费" width="100" />
        <el-table-column prop="ysjeb" label="已收电费" width="100" />
        <el-table-column prop="wsjeb" label="未收电费" width="100" />
        <el-table-column prop="kpjec" label="已开票" width="100" />
        <el-table-column prop="wkpjec" label="未开票" width="100" />
        <el-table-column prop="csyje" label="剩余可用" width="100" />
      </el-table>
      <el-pagination
        v-show="tenantTotal > 0"
        :total="tenantTotal"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        layout="total, prev, pager, next"
        @current-change="handleTenantPageChange"
        style="margin-top: 12px; text-align: right;"
      />
    </el-card>

    <!-- 租户详情弹窗 -->
    <el-dialog
      title="租户详情"
      v-model="tenantDetailVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="企业名称">{{ tenantDetail.qymc }}</el-descriptions-item>
        <el-descriptions-item label="客户编号">{{ tenantDetail.khbh }}</el-descriptions-item>
        <el-descriptions-item label="应收电费">{{ tenantDetail.hkjeb }}</el-descriptions-item>
        <el-descriptions-item label="已收电费">{{ tenantDetail.ysjeb }}</el-descriptions-item>
        <el-descriptions-item label="未收电费">{{ tenantDetail.wsjeb }}</el-descriptions-item>
        <el-descriptions-item label="已开票">{{ tenantDetail.kpjec }}</el-descriptions-item>
        <el-descriptions-item label="未开票">{{ tenantDetail.wkpjec }}</el-descriptions-item>
        <el-descriptions-item label="剩余可用">{{ tenantDetail.csyje }}</el-descriptions-item>
        <el-descriptions-item label="应收电费A">{{ tenantDetail.hkjea }}</el-descriptions-item>
        <el-descriptions-item label="已收电费A">{{ tenantDetail.ysjea }}</el-descriptions-item>
        <el-descriptions-item label="未收电费A">{{ tenantDetail.wsjea }}</el-descriptions-item>
        <el-descriptions-item label="已开票A">{{ tenantDetail.ykpjea }}</el-descriptions-item>
        <el-descriptions-item label="未开票A">{{ tenantDetail.wkpjea }}</el-descriptions-item>
        <el-descriptions-item label="已预充值">{{ tenantDetail.cczje }}</el-descriptions-item>
        <el-descriptions-item label="已扣除">{{ tenantDetail.ckcje }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="tenantDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { selectProjectPower, selectTenantPower } from "@/api/carrier/index";
import { selectzt } from "@/api/carrier/ammeter";
import { parseTime } from "@/utils/ruoyi";

const queryParams = reactive({
  zt: undefined,
  month: getLastMonthStr(),
  pageNum: 1,
  pageSize: 10,
});
const carrierList = ref([]);
const boardData = ref({});
const pieChart = ref(null);
const projectMapChart = ref(null);
const incomePieChart = ref(null);
const powerBarChart = ref(null);
const invoicePieChart = ref(null);
const tenantBarChart = ref(null);

let chartInstance = null;
let incomePieInstance = null;
let powerBarInstance = null;
let invoicePieInstance = null;
let projectMapInstance = null;
let tenantBarInstance = null;

// 租户列表相关
const tenantList = ref([]);
const tenantTotal = ref(0);
const tenantLoading = ref(false);
const tenantDetailVisible = ref(false);
const tenantDetail = ref({});

function getLastMonthStr() {
  const d = new Date();
  d.setDate(1);
  d.setMonth(d.getMonth() - 1);
  return parseTime(d, "{y}-{m}");
}

function getCarrierList() {
  selectzt({
    pageNum: 1,
    pageSize: 20,
    lxbh: 1,
  }).then(res => {
    carrierList.value = res.data?.list || [];
    if (carrierList.value.length > 0) {
      queryParams.zt = carrierList.value[0].nr;
      handleQuery();
    }
  });
}

function getBoardData() {
  selectProjectPower({
    zt: queryParams.zt,
    month: queryParams.month,
  }).then(res => {
    boardData.value = res.data || {};
    nextTick(() => {
      drawIncomePie();
      drawPowerBar();
      drawInvoicePie();
    });
  });
}

function getTenantList() {
  tenantLoading.value = true;
  selectTenantPower({
    zt: queryParams.zt,
    month: queryParams.month,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  }).then(res => {
    tenantList.value = res.data?.list || [];
    tenantTotal.value = res.data?.total || 0;
    tenantLoading.value = false;
    nextTick(() => {
      drawTenantBar();
    });
  }).catch(() => {
    tenantLoading.value = false;
  });
}

function handleQuery() {
  getBoardData();
  getTenantList();
  nextTick(() => {
    drawProjectMap();
  });
}
function resetQuery() {
  queryParams.month = getLastMonthStr();
  if (carrierList.value.length > 0) {
    queryParams.zt = carrierList.value[0].nr;
  }
  getBoardData();
  getTenantList();
  nextTick(() => {
    drawProjectMap();
  });
}

function handleTenantPageChange(page) {
  queryParams.pageNum = page;
  getTenantList();
}

function showTenantDetail(row) {
  tenantDetail.value = row;
  tenantDetailVisible.value = true;
}

// 项目分布图（可用柱状图模拟项目数量分布）
function drawProjectMap() {
  if (!projectMapChart.value) return;
  if (!projectMapInstance) {
    projectMapInstance = echarts.init(projectMapChart.value);
  }
  // 假设 carrierList.value 里每个项目有个 name 字段
  const names = carrierList.value.map(i => i.nr);
  const values = carrierList.value.map(() => Math.floor(Math.random() * 20 + 1)); // 可替换为真实项目数据
  projectMapInstance.setOption({
    title: { text: '', left: 'center' },
    tooltip: {},
    xAxis: { type: 'category', data: names, axisLabel: { color: '#666' } },
    yAxis: { type: 'value', axisLabel: { color: '#666' } },
    series: [{
      data: values,
      type: 'bar',
      itemStyle: { color: '#209ff0', borderRadius: [6,6,0,0] }
    }]
  });
}

// 营收饼图
function drawIncomePie() {
  if (!incomePieChart.value) return;
  if (!incomePieInstance) {
    incomePieInstance = echarts.init(incomePieChart.value);
  }
  incomePieInstance.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, textStyle: { color: '#fff' } },
    series: [
      {
        name: '营收比',
        type: 'pie',
        radius: ['45%', '70%'],
        label: { color: '#fff' },
        data: [
          { value: boardData.value.hkysjeb || 0, name: '租用已收' },
          { value: boardData.value.hkwsjeb || 0, name: '租用未收' },
        ]
      }
    ]
  });
}

// 电量柱状图
function drawPowerBar() {
  if (!powerBarChart.value) return;
  if (!powerBarInstance) {
    powerBarInstance = echarts.init(powerBarChart.value);
  }
  powerBarInstance.setOption({
    tooltip: {},
    xAxis: {
      type: 'category',
      data: ['电表总电量', '租用总电量', '月度整体电费', '空调费已收'],
      axisLabel: { color: '#fff' }
    },
    yAxis: { type: 'value', axisLabel: { color: '#fff' } },
    series: [{
      data: [
        boardData.value.dbjsa || 0,
        boardData.value.dbzya || 0,
        boardData.value.dbjsdfa || 0,
        boardData.value.kkysjec || 0
      ],
      type: 'bar',
      itemStyle: { color: '#006dff', borderRadius: [6,6,0,0] }
    }]
  });
}

// 开票饼图
function drawInvoicePie() {
  if (!invoicePieChart.value) return;
  if (!invoicePieInstance) {
    invoicePieInstance = echarts.init(invoicePieChart.value);
  }
  invoicePieInstance.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, textStyle: { color: '#fff' } },
    series: [
      {
        name: '开票',
        type: 'pie',
        radius: ['45%', '70%'],
        label: { color: '#fff' },
        data: [
          { value: boardData.value.kpjec || 0, name: '已开票' },
          { value: boardData.value.dkpjec || 0, name: '待开票' },
        ]
      }
    ]
  });
}

// 租户电费分布柱状图
function drawTenantBar() {
  if (!tenantBarChart.value) return;
  if (!tenantBarInstance) {
    tenantBarInstance = echarts.init(tenantBarChart.value);
  }
  const names = tenantList.value.map(i => i.qymc);
  const values = tenantList.value.map(i => i.hkjeb || 0);
  tenantBarInstance.setOption({
    tooltip: {},
    xAxis: { type: 'category', data: names, axisLabel: { color: '#666', rotate: 30 } },
    yAxis: { type: 'value', axisLabel: { color: '#666' } },
    series: [{
      data: values,
      type: 'bar',
      itemStyle: { color: '#209ff0', borderRadius: [6,6,0,0] }
    }]
  });
}

onMounted(() => {
  getCarrierList();
  nextTick(() => {
    drawProjectMap();
  });
});
watch(() => boardData.value, () => {
  drawIncomePie();
  drawPowerBar();
  drawInvoicePie();
});
watch(() => tenantList.value, drawTenantBar);
</script>

<style scoped>
.app-container {
  background: #f6faff;
  min-height: 100vh;
  padding: 24px;
}
.workbench-form {
  margin-bottom: 18px;
  background: #fff;
  border-radius: 10px;
  padding: 18px 24px 0 24px;
  box-shadow: 0 2px 12px 0 rgba(32,159,240,0.06);
}
.map-card {
  margin-bottom: 18px;
  border-radius: 14px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(32,159,240,0.08);
  padding: 18px 18px 10px 18px;
}
.map-title {
  font-size: 18px;
  font-weight: bold;
  color: #209ff0;
  margin-bottom: 8px;
}
.board-row {
  margin-bottom: 18px;
}
.board-card {
  border-radius: 14px;
  /* min-height: 340px; */
  color: #fff;
  margin-bottom: 18px;
  /* padding: 18px 18px 10px 18px; */
  box-shadow: 0 2px 12px 0 rgba(32,159,240,0.10);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.board-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #fff;
  letter-spacing: 2px;
}
.board-value-group {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 12px 0;
  margin-bottom: 8px;
}
.board-label {
  font-size: 15px;
  color: #fff;
  margin-bottom: 2px;
  font-weight: 500;
}
.board-value {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
  letter-spacing: 1px;
  line-height: 1.2;
}
.income-bg {
  background: linear-gradient(90deg, #209ff0 0%, #0079ff 100%);
}
.power-bg {
  background: linear-gradient(90deg, #67c23a 0%, #43e97b 100%);
}
.invoice-bg {
  background: linear-gradient(90deg, #b37feb 0%, #209ff0 100%);
}
.tenant-chart-card {
  border-radius: 14px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(32,159,240,0.08);
  padding: 18px 18px 10px 18px;
  margin-bottom: 18px;
}
.tenant-chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #209ff0;
  margin-bottom: 8px;
}
.tenant-list-card {
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 18px;
  margin-bottom: 18px;
}
.tenant-list-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}
</style>